package org.hsieh.tr.explore.ui;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPersistableElement;
import org.hsieh.tr.explore.dbconn.ConnectionFactory;
import org.hsieh.tr.explore.dbsource.IDatabaseInfo;
import org.hsieh.tr.explore.exception.ExceptionHandler;

/**
 * Fake input element for opening the transcation editor.
 * 
 *@author hsieh 234aini@gmail.com
 * 
 */
public final class TransactionEditorInput implements IEditorInput {

    private final IDatabaseInfo info;

    private transient static Map<IDatabaseInfo, Integer> sequences = new HashMap<IDatabaseInfo, Integer>();

    private transient static int currentSequence = 1;

    private TransactionEditorInput(final IDatabaseInfo info) throws Exception {
	this.info = info;
    }

    public static TransactionEditorInput newInput(final IDatabaseInfo info)
	    throws Exception {
	Integer sequence = sequences.get(info);
	if (sequence == null) {
	    sequences.put(info, 1);
	    currentSequence = 1;
	} else {
	    sequences.put(info, sequence + 1);
	    currentSequence = sequence + 1;
	}
	return new TransactionEditorInput(info);
    }

    public int getSequence() {
	return currentSequence;
    }

    public boolean exists() {
	return true;
    }

    public ImageDescriptor getImageDescriptor() {
	return null;
    }

    public String getName() {
	return info.getName() + "_" + getSequence();
    }

    public IPersistableElement getPersistable() {
	return null;
    }

    public String getToolTipText() {
	return info.composeUrl();
    }

    @SuppressWarnings("unchecked")
    public Object getAdapter(Class adapter) {
	if (adapter.equals(IDatabaseInfo.class)) {
	    return info;
	}
	if (adapter.equals(Connection.class)) {
	    // always create new Connection
	    try {
		return ConnectionFactory.connect(info);
	    } catch (Exception e) {
		ExceptionHandler.handle(e);
	    }
	}
	return null;
    }
}
